package cn.rkylin.oms.ext.cainiao.shiporder.controller;

import java.net.URLDecoder;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.PageInfo;

import cn.rkylin.core.controller.ApolloController;
import cn.rkylin.oms.common.consts.ShiporderStatus;
import cn.rkylin.oms.common.context.CurrentUser;
import cn.rkylin.oms.common.context.WebContextFactory;
import cn.rkylin.oms.ext.cainiao.shiporder.dao.ShiporderDAOImpl;
import cn.rkylin.oms.ext.cainiao.shiporder.dao.ShiporderSkuDAOImpl;
import cn.rkylin.oms.ext.cainiao.shiporder.service.ShiporderServiceImpl;
import cn.rkylin.oms.ext.cainiao.shiporder.vo.ShiporderSkuVO;
import cn.rkylin.oms.ext.cainiao.shiporder.vo.ShiporderVO;

@Controller
@RequestMapping("/cainiaoshiporder")
public class ShiporderControllerCaiNiao extends ApolloController {

    private static final Log logger = LogFactory.getLog(ShiporderControllerCaiNiao.class);
    private static final String PAGE_SELECT_STATEMENT = "pageSelectShiporderCaiNiao";
    private static final String PAGE_SUK_SELECT_STATEMENT = "selectShiporderSkuListCaiNiao";

    @Autowired
    private ShiporderServiceImpl cainiaoShiporderServiceImpl;

    /**
     * 查询发货单列表
     * 
     * @param quickSearch
     *            快速查询条件
     * @param formJson
     *            高级检索条件
     * @param param
     *            发货VO
     * @param start
     *            第几页
     * @param length
     *            每页多少行
     * @return 结果Map
     */
    @SuppressWarnings({ "unchecked", "rawtypes" })
    @ResponseBody
    @RequestMapping(value = "/getShiporderList")
    public Map<String, Object> getShiporderList(String quickSearch, String formJson, String shiporderStatus,
            @RequestParam(required = false, defaultValue = "0") int start, @RequestParam(required = false, defaultValue = "10") int length) {
        Map map = new HashMap();
        try {
            // 处理分页
            if (length == -1) {
                length = Integer.MAX_VALUE;
            }
            int page = start / length + 1;

            ShiporderVO param = new ShiporderVO();
            // 高级查询检索条件
            formJson = URLDecoder.decode(formJson, "UTF-8");
            param = JSONObject.parseObject(formJson, ShiporderVO.class);
            // 快速查询检索条件
            quickSearch = URLDecoder.decode(quickSearch, "UTF-8");
            if (StringUtils.isNotEmpty(quickSearch)) {
                param.setQuickSearch(quickSearch);
            }
            param.setShiporderStatus(shiporderStatus);
            CurrentUser currentUser = WebContextFactory.getWebContext().getCurrentUser();
            String prjId = currentUser.getCurrentProject().getPrjId();
            param.setPrjId(prjId);

            // 处理转义的字段
            Map<String, String> replaceFieldsMap = new HashMap<String, String>();
            replaceFieldsMap.put("enableStatus", "enable");

            // 排序语句生成
            String orderStatement = getOrderString(ShiporderDAOImpl.class.getName(), PAGE_SELECT_STATEMENT, replaceFieldsMap);
            if (StringUtils.isNotEmpty(orderStatement)) {
                param.setOrderBy(orderStatement);
            }

            PageInfo<ShiporderVO> stockInList = cainiaoShiporderServiceImpl.findByWhere(page, length, param);
            map.put(JSON_RESULT, SUCCESS);
            map.put(RECORDS_FILTERED, stockInList.getTotal());
            map.put(RECORDS_TOTAL, stockInList.getTotal());
            map.put(RETURN_DATA, stockInList.getList());

        } catch (Exception ex) {
            logger.error(ex.getMessage(), ex);
            map.put(JSON_RESULT, FAILED);
            map.put(JSON_MSG, ex.getMessage());
        }

        return map;
    }

    /**
     * jinshen 通过orderId检索发货信息
     * 
     * @param orderId
     * @param start
     * @param length
     * @return
     */
    @SuppressWarnings("unchecked")
    @ResponseBody
    @RequestMapping(value = "/getShiporderListByOrderId")
    public Map<String, Object> getShiporderListByOrderId(String orderId, @RequestParam(required = false, defaultValue = "0") int start,
            @RequestParam(required = false, defaultValue = "10") int length) {
        Map<String, Object> map = new HashMap<String, Object>();
        try {
            // 处理分页
            if (length == -1) {
                length = Integer.MAX_VALUE;
            }
            int page = start / length + 1;

            ShiporderVO param = new ShiporderVO();
            param.setSourceId(orderId);
            param.setSourceType("or");

            // 处理转义的字段
            Map<String, String> replaceFieldsMap = new HashMap<String, String>();
            replaceFieldsMap.put("enableStatus", "enable");

            // 排序语句生成
            String orderStatement = getOrderString(ShiporderDAOImpl.class.getName(), PAGE_SELECT_STATEMENT, replaceFieldsMap);
            if (StringUtils.isNotEmpty(orderStatement)) {
                param.setOrderBy(orderStatement);
            }
            CurrentUser currentUser = WebContextFactory.getWebContext().getCurrentUser();
            String prjId = currentUser.getCurrentProject().getPrjId();
            param.setPrjId(prjId);

            PageInfo<ShiporderVO> stockInList = cainiaoShiporderServiceImpl.findByWhere(page, length, param);
            map.put(JSON_RESULT, SUCCESS);
            map.put(RECORDS_FILTERED, stockInList.getTotal());
            map.put(RECORDS_TOTAL, stockInList.getTotal());
            map.put(RETURN_DATA, stockInList.getList());

        } catch (Exception ex) {
            logger.error(ex.getMessage(), ex);
            map.put(JSON_RESULT, FAILED);
            map.put(JSON_MSG, ex.getMessage());
        }

        return map;
    }

    /**
     * 查询发货单列表数量
     * 
     * @param quickSearch
     *            快速查询条件
     * @param formJson
     *            高级检索条件
     * @param param
     *            发货VO
     * @param start
     *            第几页
     * @param length
     *            每页多少行
     * @return 结果Map
     */
    @SuppressWarnings({ "unchecked", "rawtypes" })
    @ResponseBody
    @RequestMapping(value = "/getShiporderListCount")
    public Map<String, Object> getShiporderListount(String quickSearch, String formJson, String shiporderStatus,
            @RequestParam(required = false, defaultValue = "0") int start, @RequestParam(required = false, defaultValue = "10") int length) {
        Map map = new HashMap();
        try {
            Map waitSendOutGoodsMap = this.getShiporderList(quickSearch, formJson, ShiporderStatus.WAIT_SEND_OUT_GOODS, start, length);
            Map sendingOutGoodsMap = this.getShiporderList(quickSearch, formJson, ShiporderStatus.SENDING_OUT_GOODS, start, length);
            Map shipedMap = this.getShiporderList(quickSearch, formJson, ShiporderStatus.SHIPED, start, length);
            Map consignedMap = this.getShiporderList(quickSearch, formJson, ShiporderStatus.CONSIGNED, start, length);
            Map canceledMap = this.getShiporderList(quickSearch, formJson, ShiporderStatus.CANCELED, start, length);

            map.put(JSON_RESULT, SUCCESS);
            map.put("waitSendOutGoodsCount", waitSendOutGoodsMap.get(RECORDS_TOTAL));
            map.put("sendingOutGoodsCount", sendingOutGoodsMap.get(RECORDS_TOTAL));
            map.put("shipedCount", shipedMap.get(RECORDS_TOTAL));
            map.put("consignedCount", consignedMap.get(RECORDS_TOTAL));
            map.put("canceledCount", canceledMap.get(RECORDS_TOTAL));

        } catch (Exception ex) {
            logger.error(ex.getMessage(), ex);
            map.put(JSON_RESULT, FAILED);
            map.put(JSON_MSG, ex.getMessage());
        }

        return map;
    }

    /**
     * 查询发货单信息
     * 
     * @param shiporderId
     *            发货单Id
     * @return 结果Map
     * @throws Exception
     *             异常
     */
    @ResponseBody
    @RequestMapping(value = { "/getShiporderInfo/{shiporderId}" })
    public Map<String, Object> getShiporderInfo(@PathVariable String shiporderId) throws Exception {
        Map<String, Object> returnMap = new HashMap<String, Object>();
        try {
            ShiporderVO shiporderVO = new ShiporderVO();
            shiporderVO.setShiporderId(shiporderId);
            ShiporderVO data = cainiaoShiporderServiceImpl.getShiporderInfo(shiporderVO);

            returnMap.put(JSON_RESULT, SUCCESS);
            returnMap.put(RETURN_DATA, data);
        } catch (Exception ex) {
            logger.error(ex.getMessage(), ex);
            returnMap.put(JSON_RESULT, FAILED);
            returnMap.put(JSON_MSG, ex.getMessage());
        }

        return returnMap;
    }

    /**
     * 查询发货单商品列表
     * 
     * @param shiporderId
     *            发货单Id
     * @return 结果Map
     */
    @ResponseBody
    @RequestMapping(value = "/getShiporderSkuList")
    public Map<String, Object> getShiporderSkuList(String shiporderId) {
        Map<String, Object> returnMap = new HashMap<String, Object>();

        try {
            ShiporderSkuVO shiporderSkuVO = new ShiporderSkuVO();
            shiporderSkuVO.setShiporderId(shiporderId);
            // 处理转义的字段
            Map<String, String> replaceFieldsMap = new HashMap<String, String>();
            // 排序语句生成
            String orderStatement = getOrderString(ShiporderSkuDAOImpl.class.getName(), PAGE_SUK_SELECT_STATEMENT, replaceFieldsMap);
            if (StringUtils.isNotEmpty(orderStatement)) {
                shiporderSkuVO.setOrderBy(orderStatement);
            }

            List<ShiporderSkuVO> shiporderSkuVOList = cainiaoShiporderServiceImpl.selectShiporderSkuList(shiporderSkuVO);

            returnMap.put(JSON_RESULT, SUCCESS);
            returnMap.put(RETURN_DATA, shiporderSkuVOList);
        } catch (Exception ex) {
            logger.error(ex.getMessage(), ex);
            returnMap.put(JSON_RESULT, FAILED);
            returnMap.put(JSON_MSG, ex.getMessage());
        }

        return returnMap;
    }
}
